package com.dianxin.smartpark.service.attendance.impl;

import cn.hutool.core.date.DateUtil;
import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.constant.ErrMsgEnum;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.dianxin.smartpark.dao.dataobject.attendance.SmartParkShift;
import com.dianxin.smartpark.dao.dataobject.attendance.SmartParkShiftDetails;
import com.dianxin.smartpark.dao.dataobject.attendance.SmartParkShiftDetailsExample;
import com.dianxin.smartpark.dao.dataobject.attendance.SmartParkShiftExample;
import com.dianxin.smartpark.dao.mapper.attendance.SmartParkShiftDetailsMapper;
import com.dianxin.smartpark.dao.mapper.attendance.SmartParkShiftMapper;
import com.dianxin.smartpark.dao.qo.attendance.SmartParkShiftDetailsQO;
import com.dianxin.smartpark.dao.qo.attendance.SmartParkShiftQO;
import com.dianxin.smartpark.service.attendance.SmartParkShiftService;
import com.dianxin.smartpark.service.utils.DateTimeUtil;
import com.dianxin.smartpark.service.vo.attendance.SmartParkShiftVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: smart-park
 * @description:
 * @author: chenyong
 * @create: 2021-07-23 16:06
 */
@Service
public class SmartParkShiftServiceImpl implements SmartParkShiftService {
    private final static Logger logger = LoggerFactory.getLogger(SmartParkShiftServiceImpl.class);

    @Resource
    private SmartParkShiftMapper smartParkShiftMapper;
    @Resource
    private SmartParkShiftDetailsMapper smartParkShiftDetailsMapper;


    /**
     * @Description:  分页
     * @Author: ChenYong
     * @Date: 2021/7/26 0026
     * @param smartParkShiftQO:
     * @Return: CommonResponseBody<List<SmartParkShiftVO>>
     */
    @Override
    public CommonResponseBody<List<SmartParkShiftVO>> getShifts(SmartParkShiftQO smartParkShiftQO) {
        SmartParkShiftExample recordExample = new SmartParkShiftExample();
        SmartParkShiftExample.Criteria criteria = recordExample.createCriteria();
        criteria.andIsDeletedEqualTo(0);
        if(StringUtils.isBlank(smartParkShiftQO.getTenantId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
        }
        if (StringUtils.isNotBlank(smartParkShiftQO.getTenantId())) {
            criteria.andTenantIdEqualTo(smartParkShiftQO.getTenantId());
        }
        if (smartParkShiftQO.getEnableStatus()!=null) {
            criteria.andEnableStatusEqualTo(smartParkShiftQO.getEnableStatus());
        }
        if (smartParkShiftQO.getNeedPage()) {
            recordExample.setOrderByClause("gmt_create desc limit " + (smartParkShiftQO.getPageIndex() - 1) * smartParkShiftQO.getPageSize() + "," + smartParkShiftQO.getPageSize());
        } else {
            recordExample.setOrderByClause("gmt_create desc");
        }
        List<SmartParkShift> smartParkShifts = new ArrayList<>();
        if (!smartParkShiftQO.getNeedPage()) {
            SmartParkShift smartParkShift = new SmartParkShift();
            smartParkShift.setId(0L);
            smartParkShift.setShiftName("休息");
            smartParkShift.setIsDeleted(0);
            smartParkShifts.add(smartParkShift);
        }
        List<SmartParkShift> passRecords = smartParkShiftMapper.selectByExample(recordExample);
        for (SmartParkShift smartParkShift:passRecords){
            SmartParkShiftDetailsExample smartParkShiftDetailsExample = new SmartParkShiftDetailsExample();
            smartParkShiftDetailsExample.or().andShiftIdEqualTo(smartParkShift.getId()).andIsDeletedEqualTo(0);
            List<SmartParkShiftDetails> smartParkShiftDetailsList = smartParkShiftDetailsMapper.selectByExample(smartParkShiftDetailsExample);
            smartParkShift.setDetailVOList(smartParkShiftDetailsList);
            smartParkShifts.add(smartParkShift);
        }
        long count = smartParkShiftMapper.countByExample(recordExample);

        return ResponseBodyWrapperUtil
                .successListWrapper(smartParkShifts, count, smartParkShiftQO, SmartParkShiftVO.class);
    }

    /**
     * @Description:  新增
     * @Author: ChenYong
     * @Date: 2021/7/26 0026
     * @param smartParkShiftQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody saveShift(SmartParkShiftQO smartParkShiftQO) {
        SmartParkShift smartParkShift = new SmartParkShift();
        String format = "hh:mm";
        if(StringUtils.isBlank(smartParkShiftQO.getTenantId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
        }
        try {
            BeanUtil.conversion(smartParkShiftQO,smartParkShift);
            smartParkShift.beforeInsert();
            if(smartParkShiftQO.getDetailVOList()!=null&&smartParkShiftQO.getDetailVOList().size()<0){
                return ResponseBodyWrapperUtil.fail("打卡时段不能为空","60004");
            }

            for (int i = 0; i <smartParkShiftQO.getDetailVOList().size() ; i++) {
                //当前数据
                SmartParkShiftDetailsQO smartParkShiftDetailsQO = new SmartParkShiftDetailsQO();
                //前一条数据
                SmartParkShiftDetailsQO shiftDetailsQO = new SmartParkShiftDetailsQO();
                smartParkShiftDetailsQO = smartParkShiftQO.getDetailVOList().get(i);
                //判断必要参数是否为空
                if(StringUtils.isEmpty(smartParkShiftDetailsQO.getSignInTime())&&StringUtils.isEmpty(smartParkShiftDetailsQO.getSignInStartTime())&&StringUtils.isEmpty(smartParkShiftDetailsQO.getSignInEndTime())&&StringUtils.isEmpty(smartParkShiftDetailsQO.getSignOutTime())&&StringUtils.isEmpty(smartParkShiftDetailsQO.getSignOutStartTime())&&StringUtils.isEmpty(smartParkShiftDetailsQO.getSignOutEndTime())){
                    return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(),ErrMsgEnum.EMPTY_PARAME.getErrorCode());
                }
                //获取签到时间
                Date SignInTime = DateUtil.parse(smartParkShiftDetailsQO.getSignInTime(), format);
                //获取签退时间
                Date SignOutTime = DateUtil.parse(smartParkShiftDetailsQO.getSignOutTime(), format);
                if(SignOutTime.before(SignInTime)){
                    return ResponseBodyWrapperUtil.fail("签退时间不能在签到时间之前","60001");
                }
                //签到时间是否在签到时间段内
                boolean SignInEffectiveDate = DateTimeUtil.isEffectiveDate(smartParkShiftDetailsQO.getSignInTime(), smartParkShiftDetailsQO.getSignInStartTime(), smartParkShiftDetailsQO.getSignInEndTime());
                if(!SignInEffectiveDate){
                    return ResponseBodyWrapperUtil.fail("签到时间不在签到时间段内","60002");
                }
                //判断签退时间是否在签退时间段内
                boolean SignOutEffectiveDate1 = DateTimeUtil.isEffectiveDate(smartParkShiftDetailsQO.getSignOutTime(), smartParkShiftDetailsQO.getSignOutStartTime(), smartParkShiftDetailsQO.getSignOutEndTime());
                if(!SignOutEffectiveDate1){
                    return ResponseBodyWrapperUtil.fail("签退时间不在签退时间段内","60003");
                }

                //判断是否是第一条数据，如果不是判断当前签到时间是否大于签退时间
                if(i != 0){
                    shiftDetailsQO = smartParkShiftQO.getDetailVOList().get(i-1);
                    if(DateUtil.parse(shiftDetailsQO.getSignInTime(), format).before(SignOutTime)){
                        return ResponseBodyWrapperUtil.fail("签到时间应大于上一条的签退时间","60004");
                    }
                }
            }
            SmartParkShiftDetailsQO detailsQO = smartParkShiftQO.getDetailVOList().get(smartParkShiftQO.getDetailVOList().size()-1);
            if(DateUtil.parse(detailsQO.getSignOutTime(), format).after(DateUtil.parse("23:50", format))){
                return ResponseBodyWrapperUtil.fail("签退时间不能超过凌晨12点","60006");
            }

            //保存班次和班次详情
            int insert = smartParkShiftMapper.insert(smartParkShift);
            for (SmartParkShiftDetailsQO smartParkShiftDetailsQO : smartParkShiftQO.getDetailVOList()){
                SmartParkShiftDetails smartParkShiftDetails = new SmartParkShiftDetails();
                smartParkShiftDetailsQO.setShiftId(smartParkShift.getId());
                smartParkShiftDetailsQO.setTenantId(smartParkShift.getTenantId());
                BeanUtil.conversion(smartParkShiftDetailsQO,smartParkShiftDetails);
                smartParkShiftDetails.beforeInsert();
                smartParkShiftDetailsMapper.insert(smartParkShiftDetails);
            }

            return ResponseBodyWrapperUtil.toResData(insert);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

    /**
     * @Description:  修改
     * @Author: ChenYong
     * @Date: 2021/7/26 0026
     * @param smartParkShiftQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody updateShift(SmartParkShiftQO smartParkShiftQO) {
        SmartParkShift smartParkShift = new SmartParkShift();
        if(StringUtils.isBlank(smartParkShiftQO.getTenantId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
        }
        try {
            BeanUtil.conversion(smartParkShiftQO,smartParkShift);
            smartParkShift.beforeInsert();
            smartParkShift.beforeUpdate();
            int update = smartParkShiftMapper.updateByPrimaryKey(smartParkShift);
            if(update>0){
                int delete = smartParkShiftDetailsMapper.deleteByShiftDetail(smartParkShiftQO.getId());
                if(delete>0){
                    for (SmartParkShiftDetailsQO smartParkShiftDetailsQO : smartParkShiftQO.getDetailVOList()){
                        SmartParkShiftDetails smartParkShiftDetails = new SmartParkShiftDetails();
                        smartParkShiftDetailsQO.setShiftId(smartParkShift.getId());
                        smartParkShiftDetailsQO.setTenantId(smartParkShift.getTenantId());
                        BeanUtil.conversion(smartParkShiftDetailsQO,smartParkShiftDetails);
                        smartParkShiftDetails.beforeInsert();
                        smartParkShiftDetailsMapper.insert(smartParkShiftDetails);
                    }
                }
            }
            return ResponseBodyWrapperUtil.toResData(update);
        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

    /**
     * @Description:  删除
     * @Author: ChenYong
     * @Date: 2021/7/26 0026
     * @param ids:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody deleteShift(Long[] ids) {
        int status = 0;
        for (Long id :ids){
            SmartParkShift smartParkShift = smartParkShiftMapper.selectByPrimaryKey(id);
            smartParkShift.setIsDeleted(1);
            smartParkShift.beforeDelete();
            smartParkShiftDetailsMapper.deleteByShiftDetail(id);
            status = smartParkShiftMapper.updateByPrimaryKey(smartParkShift);
        }
        return ResponseBodyWrapperUtil.toResData(status);
    }

    /**
     * @Description:  获取班次详情信息
     * @Author: ChenYong
     * @Date: 2021/7/30 0030
     * @param smartParkShiftQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody shiftDetails(SmartParkShiftQO smartParkShiftQO) {
        SmartParkShiftVO smartParkShiftVO = new SmartParkShiftVO();
        try {
            SmartParkShift smartParkShift = smartParkShiftMapper.selectByPrimaryKey(smartParkShiftQO.getId());
            SmartParkShiftDetailsExample smartParkShiftDetailsExample = new SmartParkShiftDetailsExample();
            smartParkShiftDetailsExample.or().andShiftIdEqualTo(smartParkShift.getId()).andIsDeletedEqualTo(0);
            List<SmartParkShiftDetails> smartParkShiftDetailsList = smartParkShiftDetailsMapper.selectByExample(smartParkShiftDetailsExample);
            smartParkShift.setDetailVOList(smartParkShiftDetailsList);
            BeanUtil.conversion(smartParkShift,smartParkShiftVO);
            return ResponseBodyWrapperUtil.successWrapper(smartParkShiftVO);
        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

}
